package com.zzh.takeoutapp.activity;

import android.content.Intent;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.ClassifyAdapter;
import com.zzh.takeoutapp.base.BaseActivity;
import com.zzh.takeoutapp.config.Constants;
import com.zzh.takeoutapp.config.UrlConfig;
import com.zzh.takeoutapp.entity.HomeShopEntity;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.DividerGridItemDecoration;
import com.zzh.takeoutapp.utils.GsonResolve;
import com.zzh.takeoutapp.utils.LoadingUtil;
import com.zzh.takeoutapp.utils.NetWorkUtils;
import com.zzh.takeoutapp.utils.SPUtils;
import com.zzh.takeoutapp.utils.ToolBarHelper;
import com.zzh.takeoutapp.view.DiscountsView;
import com.zzh.takeoutapp.view.FilterView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/7/25.
 * 商家列表数据
 */

public class ClassifyActivity extends BaseActivity implements OnRefreshListener, OnLoadmoreListener {
    @Bind(R.id.tv_empty_text)
    TextView tv_empty_text;
    @Bind(R.id.empty_text)
    NestedScrollView mEmptyLayout;//设置没有数据网络的情况
    @Bind(R.id.toolbar)
    Toolbar tbToolbar;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.discounts_view)
    DiscountsView discountsView;
    @Bind(R.id.view_filter_basic)
    FilterView realFilterView;
    @Bind(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    private ClassifyAdapter adapter;
    private List<HomeShopEntity.DataBean.ItemsBean> stringList;
    private DiscountsView discView;
    private GridLayoutManager layoutManager;
    private int mIndex = 0;
    private boolean idonSortClick = false;//判断监听
    private boolean isClickListenerFisrt;
    private int screenPosition = 0;
    public static final String HOMESALESVOLUME = "tvHomeSalesVolume";
    public static final String HOMEDISTANCE = "tvHomeDistance";
    public static final String HOMESCREEN = "lvHome_Screen";
    private String cate_id;
    private int CURPAGE = 1;//加载页码
    private final String CLASSIFY_ACTIVITY = "ClassifyActivity";
    private final String CONDITION_SERVICE = "ConditionServices";
    private final String ON_ITEM_CLICK = "onItemClick";
    private final String YOU_HUI_FILTER = "youhui_filter";
    private final String PEI_FILTER = "pei_filter";
    private LoadingUtil loadingUtil;

    @Override
    public void setContent() {
        setContentView(R.layout.activity_classif);
        ButterKnife.bind(this);
        loadingUtil = new LoadingUtil(this);
        adapter = new ClassifyAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadmoreListener(this);
        mRefreshLayout.setDisableContentWhenRefresh(true);
        mRefreshLayout.setDisableContentWhenLoading(true);
    }

    @Override
    public void initComponent() {
        ToolBarHelper.setTitleAndBackAndText(this, tbToolbar, getIntent().getStringExtra("ClassifyValue"));
        layoutManager = new GridLayoutManager(this, 1);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerGridItemDecoration(this, 0, R.color.blue));
        stringList = new ArrayList<>();
        cate_id = getIntent().getStringExtra("cate_id");
        initSeevice("", "", "", "", cate_id);
    }

    @Override
    public void setListener() {
        recyclerView.addOnScrollListener(scrollListener);
        realFilterView.setOnFilterClickListener(new FilterView.OnFilterClickListener() {
            @Override
            public void onFilterClick(int position) {
                screenPosition = position;
                if (screenPosition == 0) {
                    realFilterView.show(screenPosition);
                } else {
                    realFilterView.show(screenPosition);
                }
                idonSortClick = false;
            }
        });
    }


    RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int n = Math.abs(mIndex - layoutManager.findFirstVisibleItemPosition());
            if (n >= 2) {
                discountsView.setVisibility(View.VISIBLE);
            } else if (n < 1) {
                discountsView.setVisibility(View.GONE);
            }
            if (n >= 1) {
                if (dy > 0) {
                    realFilterView.setVisibility(View.GONE);
                    if (screenPosition == 2) {
                        realFilterView.setVisibility(View.VISIBLE);
                        screenPosition = 0;
                    }
                    if (idonSortClick == true) {
                        realFilterView.setVisibility(View.VISIBLE);
                        idonSortClick = false;
                        if (screenPosition == 0) {
                            realFilterView.show(screenPosition);
                        } else {
                            realFilterView.show(screenPosition);
                        }
                    }
                } else {
                    realFilterView.setVisibility(View.VISIBLE);
                    idonSortClick = false;
                }
            } else if (n < 1) {
                realFilterView.setVisibility(View.GONE);
            }

        }

        public void onScrollStateChanged(RecyclerView recyclerView,
                                         int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        EventbusHelper.register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventbusHelper.unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void smoothMoveToPosition(int n) {

        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            recyclerView.smoothScrollToPosition(n);
        } else if (n <= lastItem) {
            int top = recyclerView.getChildAt(n - firstItem).getTop();
            recyclerView.smoothScrollBy(0, top);
        } else {
            recyclerView.smoothScrollToPosition(n);
        }

    }


    @Override
    public void onAfterInit() {

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
    }

    /**
     * 设置颜色
     */
    private void loadingColor() {
        CURPAGE = 1;
        realFilter();
        setColor();
        loadingUtil.startShowLoading();
    }

    private void setmRefreshLayout() {
        loadingUtil.startShowLoading();
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadmore();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(NetMsgEvent event) {
        String _msgType = (String) event.getMsgType();
        JSONObject jsonObject = event.getMsgJSONObj();
        switch (_msgType) {
            case YOU_HUI_FILTER://优惠
                loadingColor();
                initSeevice(event.getErrorString(), "", "", "", cate_id);
                break;
            case PEI_FILTER://配送
                loadingColor();
                initSeevice("", "", event.getErrorString(), "", cate_id);
                break;
            case ON_ITEM_CLICK://距离
                loadingColor();
                initSeevice("", "", "", event.getErrorString(), cate_id);
                break;
            case HOMESALESVOLUME://销量
                CURPAGE = 1;
                idonSortClick = false;
                realFilterView.getTvHomeSalesVolume().setTextColor(getResources().getColor(R.color.color_red));
                realFilterView.getTvHomeDistance().setTextColor(getResources().getColor(R.color.font_black_5));
                loadingUtil.startShowLoading();
                screenPosition = 2;
                smoothMoveToPosition(1);
                setColor();
                initSeevice("", "", "", "juli", cate_id);
                break;
            case HOMEDISTANCE://距离
                CURPAGE = 1;
                idonSortClick = false;
                realFilterView.getTvHomeSalesVolume().setTextColor(getResources().getColor(R.color.font_black_5));
                realFilterView.getTvHomeDistance().setTextColor(getResources().getColor(R.color.color_red));
                loadingUtil.startShowLoading();
                screenPosition = 2;
                smoothMoveToPosition(1);
                setColor();
                initSeevice("", "", "", "juli", cate_id);
                break;
            case HOMESCREEN:
                screenPosition = 1;
                idonSortClick = true;
                if (event.getStatusCode() == 10) {
                    idonSortClick = false;
                }
                smoothMoveToPosition(1);
                break;
            case CLASSIFY_ACTIVITY:
                setmRefreshLayout();
                initData(jsonObject);
                break;
            case CONDITION_SERVICE:
                loadingData(jsonObject);
                break;
            default:
                break;
        }
    }

    private void loadingData(JSONObject jsonObject) {
        if (jsonObject != null)
            if (jsonObject.optString("error").equals("0")) {
                JSONObject data = jsonObject.optJSONObject("data");
                JSONObject orderby = data.optJSONObject("orderby");
                JSONObject youhui = data.optJSONObject("youhui");
                JSONObject pei_type = data.optJSONObject("pei_type");
                JSONObject ts = data.optJSONObject("ts");
                Map<String, String> stringStringMap = getKey(orderby.toString());
                Map<String, String> youhuiMap = getKey(youhui.toString());
                Map<String, String> pei_typeMap = getKey(pei_type.toString());
                Map<String, String> tsMap = getKey(ts.toString());
                pei_typeMap.putAll(tsMap);
                realFilterView.setTag2list(pei_typeMap);
                realFilterView.setHistorylist(youhuiMap);
                realFilterView.setSizeTaglist(stringStringMap);
                realFilterView.setOnFilterClickListener(new FilterView.OnFilterClickListener() {
                    @Override
                    public void onFilterClick(int position) {
                        screenPosition = position;
                        if (screenPosition == 0) {
                            realFilterView.show(screenPosition);
                        } else {
                            realFilterView.show(screenPosition);
                        }
                        idonSortClick = false;
                    }
                });

            }
    }

    private void initData(JSONObject jsonObject) {
        loadingUtil.stopShowLoading();
        idonSortClick = false;
        if (jsonObject != null)
            if (jsonObject.optString("error").equals("0")) {
                ServiceUrl.ConditionService(this, CONDITION_SERVICE);
                mEmptyLayout.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
                HomeShopEntity homeShopEntity = GsonResolve.jsonString2Bean(jsonObject.toString(), HomeShopEntity.class);
                if (stringList != null) {
                    stringList.clear();
                }
                stringList.addAll(homeShopEntity.getData().getItems());
                if (CURPAGE == 1) {
                    adapter.setEntity(stringList);
                    adapter.notifyItemChanged(3);
                } else {
                    adapter.insert(homeShopEntity.getData().getItems(), adapter.getItemCount());
                }
                if (homeShopEntity.getData().getItems() == null || homeShopEntity.getData().getItems().size() < 10) {
                    mRefreshLayout.setLoadmoreFinished(false);
                } else {
                    CURPAGE++;

                }
                adapter.setmOnItemClickLitener(new ClassifyAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, int postion) {
                        Intent intent = new Intent(ClassifyActivity.this, OrderCarDatelisActivity.class);
                        intent.putExtra("shop_id", adapter.getEntity().get(postion).getWaimai().getShop_id());
                        startActivity(intent);
                    }

                    @Override
                    public void onItemLongClick(View v, int postion) {
                        //moveToPosition(0);
                    }
                });

                adapter.setOnSortClick(new ClassifyAdapter.TextSortOnClickListener() {
                    @Override
                    public void onSortClick(View v, int postion, boolean isFirst) {
                        switch (v.getId()) {
                            case R.id.discounts_view://满减优惠
                                discView = (DiscountsView) v;
                                idonSortClick = false;
                                isClickListenerFisrt = true;
                                smoothMoveToPosition(2);
                                setColor(discountsView, postion);
                                break;
                        }
                    }

                    @Override
                    public void onSortClick(View v, int postion) {
                        switch (v.getId()) {
                            case R.id.filter_view://综合排序
                                screenPosition = postion;
                                idonSortClick = true;
                                smoothMoveToPosition(1);
                                break;
                        }
                    }
                });
                discountsView.setOnDiscountClickListener(new DiscountsView.OnDiscountClickListener() {
                    @Override
                    public void onDiscountClick(int position) {
                        if (isClickListenerFisrt == false) {
                            discView = adapter.getHolder().getReal_filterView();
                        }
                        setColor(discView, position);
                    }
                });
            }
    }

    private void setColor() {
        if (discountsView != null && discView != null) {
            discountsView.getTvHomeDiscounts().setBackgroundResource(R.color.font_black_6);
            discountsView.getTvHomeGratis().setBackgroundResource(R.color.font_black_6);
            discountsView.getTvHomeMerchant().setBackgroundResource(R.color.font_black_6);
            discView.getTvHomeDiscounts().setBackgroundResource(R.color.font_black_6);
            discView.getTvHomeGratis().setBackgroundResource(R.color.font_black_6);
            discView.getTvHomeMerchant().setBackgroundResource(R.color.font_black_6);
        }
    }

    //距离的颜色
    private void realFilter() {
        realFilterView.getTvHomeSalesVolume()
                .setTextColor(getResources().getColor(R.color.font_black_5));
        realFilterView.getTvHomeDistance()
                .setTextColor(getResources().getColor(R.color.font_black_5));
        if (adapter != null) {
            adapter.getTypetypeHolder().getFilterView()
                    .getTvHomeSalesVolume().setTextColor(getResources().getColor(R.color.font_black_5));
            adapter.getTypetypeHolder().getFilterView()
                    .getTvHomeDistance().setTextColor(getResources().getColor(R.color.font_black_5));
        }
    }

    /**
     * 设置颜色
     *
     * @param postion
     */
    private void setColor(DiscountsView discView, int postion) {
        if (postion == 0) {
            discView.getTvHomeDiscounts().setBackgroundResource(R.color.yellow);
            discView.getTvHomeGratis().setBackgroundResource(R.color.font_black_6);
            discView.getTvHomeMerchant().setBackgroundResource(R.color.font_black_6);
        } else if (postion == 1) {
            discView.getTvHomeDiscounts().setBackgroundResource(R.color.font_black_6);
            discView.getTvHomeGratis().setBackgroundResource(R.color.yellow);
            discView.getTvHomeMerchant().setBackgroundResource(R.color.font_black_6);
        } else if (postion == 2) {
            discView.getTvHomeDiscounts().setBackgroundResource(R.color.font_black_6);
            discView.getTvHomeGratis().setBackgroundResource(R.color.font_black_6);
            discView.getTvHomeMerchant().setBackgroundResource(R.color.yellow);
        }
        realFilter();
    }

    /**
     * 请求
     *
     * @param youhui
     * @param feature
     * @param pei
     * @param str
     * @param id
     */
    private void initSeevice(String youhui, String feature, String pei, String str, String id) {
        ServiceUrl.FiltrateServiceUrl(this,
                SPUtils.getString(this, Constants.ALL_LATITUDE, ""),
                SPUtils.getString(this, Constants.ALL_LONGITUDE, ""),
                youhui,
                feature,
                pei,
                "",
                str,
                CURPAGE,
                CLASSIFY_ACTIVITY);
    }

    private Map<String, String> getKey(String cityStr) {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        Map<String, String> stringStringMap = gson.fromJson(cityStr, new
                TypeToken<Map<String, String>>() {
                }.getType());
        return stringStringMap;
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        CURPAGE = 1;
        if (NetWorkUtils.notNetWork(this) == false) {//没有网络
            mEmptyLayout.setVisibility(View.VISIBLE);
            tv_empty_text.setText("没有网络");
            recyclerView.setVisibility(View.GONE);
            refreshlayout.finishRefresh();
        } else {
            initSeevice("", "", "", "", cate_id);
        }

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        initSeevice("", "", "", "", cate_id);
    }

}
